package com.example.healkep.MainActivity;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.healkep.R;
import com.example.healkep.auth.HealthKitAuthActivity;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;
import com.huawei.hms.hihealth.HealthRecordController;
import com.huawei.hms.hihealth.HuaweiHiHealth;
import com.huawei.hms.hihealth.data.DataType;
import com.huawei.hms.hihealth.data.Field;
import com.huawei.hms.hihealth.data.HealthDataTypes;
import com.huawei.hms.hihealth.data.HealthRecord;
import com.huawei.hms.hihealth.data.SamplePoint;
import com.huawei.hms.hihealth.data.SampleSet;
import com.huawei.hms.hihealth.data.Value;
import com.huawei.hms.hihealth.options.HealthRecordReadOptions;
import com.huawei.hms.hihealth.result.HealthRecordReply;

import org.json.JSONArray;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class MainActivityShowSleep extends Activity {

    private int[] day_sleep = new int[3];

    private String id = com.example.healkep.LoginActivity.getUser();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate ( savedInstanceState );
        setContentView ( R.layout.activity_show_sleep );
        final TextView date = findViewById ( R.id.date );
        Button button2 = findViewById ( R.id.login );
        Button button1 = findViewById ( R.id.choose );
        date.setText(LocalDate.now().toString());
        Calendar calendar = Calendar.getInstance();
        date.setOnClickListener((i)->{
            new DatePickerDialog(MainActivityShowSleep.this, (view, year, month, dayOfMonth) -> {
                LocalDate date1 = LocalDate.of(year, month+1, dayOfMonth);
                date.setText(date1.toString());
            },calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)).show();
        });
        HealthRecordController healthRecordController = HuaweiHiHealth.getHealthRecordController(this);

        //绑定监听事件
        button1.setOnClickListener ( new View.OnClickListener () {
            @Override
            public void onClick(View view) {
                new Thread ( new Runnable () {
                    @Override
                    public void run() {
                        try {
                            String finaldate = date.getText ().toString ();
                            System.out.println ( finaldate );
                            final String json ="{\n" +
                                    "    \"user\":\""+id+"\",\n" +
                                    "    \"cdate\":\""+finaldate+"\"\n" +
                                    "}";
                            OkHttpClient client = new OkHttpClient ();  //创建http客户端
                            Request request = new Request.Builder (  )
                                    .url ( com.example.healkep.LoginActivity.url+"/sleep/day" )
                                    .post ( RequestBody.create ( MediaType.parse ( "application/json"),json  ) )
                                    .build ();
                            Response response = client.newCall ( request ).execute ();  //执行发送的指令
                            String responseData = response.body ().string ();
                            JSONArray jsonArray = new JSONArray ( responseData );
                            Arrays.fill(day_sleep, 0);
                            for (int i = 0; i < jsonArray.length (); i++) {
                                if (jsonArray.getJSONObject(i).getInt("id") == 1)
                                    day_sleep[0]= day_sleep[0] + (int)(jsonArray.getJSONObject(i).getDouble("len") );
                                if (jsonArray.getJSONObject(i).getInt("id") == 2)
                                    day_sleep[1]= day_sleep[1] + (int)(jsonArray.getJSONObject(i).getDouble("len") );
                                if (jsonArray.getJSONObject(i).getInt("id") == 3)
                                    day_sleep[2]= day_sleep[2] + (int)(jsonArray.getJSONObject(i).getDouble("len") );

                            }
                            System.out.println ( "day_sleep: " );
                            System.out.println ( day_sleep[0] );
                            System.out.println ( day_sleep[1] );
                            System.out.println ( day_sleep[2] );
                            runOnUiThread ( new Runnable () {
                                @Override
                                public void run() {
                                    Toast.makeText ( MainActivityShowSleep.this, "信息获取成功", Toast.LENGTH_SHORT ).show ();

                                }
                            } );
                        } catch (Exception e) {
                            e.printStackTrace ();
                            runOnUiThread ( new Runnable () {
                                @Override
                                public void run() {
                                    Toast.makeText ( MainActivityShowSleep.this, "网络连接失败", Toast.LENGTH_SHORT ).show ();
                                }
                            } );
                        }
                    }
                } ).start ();
            }
        } );

        button2.setOnClickListener ( new View.OnClickListener () {
            @Override
            public void onClick(View view) {
                LocalDate date1 = LocalDate.parse(date.getText().toString());
                Calendar cal = new GregorianCalendar(date1.getYear(),date1.getMonthValue()-1,date1.getDayOfMonth(),0,0,0);
                long startTime = cal.getTimeInMillis();
                cal.add(Calendar.DAY_OF_MONTH,1);
                long endTime = cal.getTimeInMillis();
                List<DataType> subDataTypeList = new ArrayList<>();
                subDataTypeList.add(DataType.DT_CONTINUOUS_SLEEP);
                HealthRecordReadOptions healthRecordReadOptions =
                        new HealthRecordReadOptions.Builder().setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)
                                .readHealthRecordsFromAllApps()
                                .readByDataType(HealthDataTypes.DT_HEALTH_RECORD_SLEEP)
                                .setSubDataTypeList(subDataTypeList)
                                .build();
                Task<HealthRecordReply> task = healthRecordController.getHealthRecord(healthRecordReadOptions);
                task.addOnSuccessListener(new OnSuccessListener<HealthRecordReply>() {
                    @Override
                    public void onSuccess(HealthRecordReply readResponse) {
                        // 打印调用接口获取的健康记录列表
                        List<HealthRecord> recordList = readResponse.getHealthRecords();
                        for (HealthRecord record : recordList) {
                            if (record == null) {
                                continue;
                            }
                            Map<String, Value> map = record.getFieldValues();
                            try{
                                day_sleep[2]+=map.get("light_sleep_time(i)").asIntValue();
                                day_sleep[0]+=map.get("deep_sleep_time(i)").asIntValue();
                                day_sleep[1]+=map.get("dream_time(i)").asIntValue();
                            }catch (NullPointerException e){
                                e.printStackTrace();
                            }

                            /*dumpHealthRecord(record);
                            for (SampleSet dataSet : record.getSubDataDetails()) {
                                dumpDataSet(dataSet);
                            }*/
                        }
                        // 给bnt1添加点击响应事件
                        Intent intent2 = new Intent ( MainActivityShowSleep.this, MainActivityShowSleepDay.class );
                        Bundle bun = new Bundle ();
                        bun.putIntArray("day_sleep", day_sleep);
                        intent2.putExtras ( bun );
                        //启动
                        startActivity ( intent2 );
                    }
                });
                task.addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(Exception e) {
                        Toast.makeText(MainActivityShowSleep.this,"尚未授权",Toast.LENGTH_SHORT).show();
                        Intent intent2 = new Intent ( MainActivityShowSleep.this, HealthKitAuthActivity.class );
                        startActivity(intent2);
                    }
                });

            }
        } );

    }
    private void dumpHealthRecord(HealthRecord healthRecord) {
        DateFormat dateFormat = DateFormat.getDateInstance();
        DateFormat timeFormat = DateFormat.getTimeInstance();
        if (healthRecord != null) {
            System.out.println("\tHealthRecordIdentifier: " + healthRecord.getHealthRecordId() + "\n\tpackageName: "
                    + healthRecord.getDataCollector().getPackageName() + "\n\tStartTime: "
                    + dateFormat.format(healthRecord.getStartTime(TimeUnit.MILLISECONDS)) + " "
                    + timeFormat.format(healthRecord.getStartTime(TimeUnit.MILLISECONDS)) + "\n\tEndTime: "
                    + dateFormat.format(healthRecord.getEndTime(TimeUnit.MILLISECONDS)) + " "
                    + timeFormat.format(healthRecord.getEndTime(TimeUnit.MILLISECONDS)) + "\n\tHealthRecordDataType: "
                    + healthRecord.getDataCollector().getDataType().getName() + "\n\tHealthRecordDataCollectorId: "
                    + healthRecord.getDataCollector().getDataStreamId() + "\n\tmetaData: " + healthRecord.getMetadata()
                    + "\n\tFileValueMap: " + healthRecord.getFieldValues());

            if (healthRecord.getSubDataSummary() != null && !healthRecord.getSubDataSummary().isEmpty()) {
                SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

                for (SamplePoint samplePoint : healthRecord.getSubDataSummary()) {
                    System.out.println("Sample point type: " + samplePoint.getDataType().getName());
                    System.out.println("Start: " + sDateFormat.format(new Date(samplePoint.getStartTime(TimeUnit.MILLISECONDS))));
                    System.out.println("End: " + sDateFormat.format(new Date(samplePoint.getEndTime(TimeUnit.MILLISECONDS))));
                    for (Field field : samplePoint.getDataType().getFields()) {
                        System.out.println("Field: " + field.getName() + " Value: " + samplePoint.getFieldValue(field));
                    }
                    System.out.println(System.lineSeparator());
                }
            }
        }
    }
    private void dumpDataSet(SampleSet sampleSet) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for (SamplePoint samplePoint : sampleSet.getSamplePoints()) {
            System.out.println("Sample point type: " + samplePoint.getDataType().getName());
            System.out.println("Start: " + dateFormat.format(new Date(samplePoint.getStartTime(TimeUnit.MILLISECONDS))));
            System.out.println("End: " + dateFormat.format(new Date(samplePoint.getEndTime(TimeUnit.MILLISECONDS))));
            for (Field field : samplePoint.getDataType().getFields()) {
                System.out.println("Field: " + field.getName() + " Value: " + samplePoint.getFieldValue(field));
            }
        }
    }
    @Override
    protected  void onResume() {
        super.onResume();
        Arrays.fill(day_sleep, 0);
    }
}
